#include "ipcd.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h> // variable argument lists
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h> // POSIX shared memory
#include <semaphore.h>
#include <fcntl.h> // for O_CREAT
#include <errno.h>
#include <unistd.h>
#include <syslog.h>
#include <string.h>
#include <time.h>

void log_message(char *filename, const char* format, ...) {
	FILE *logfile;
	logfile = fopen(filename, "a");
	if (!logfile) return;
	va_list list;
	va_start( list, format );
	vfprintf(logfile, format, list);
	va_end( list );
	fprintf(logfile, "\n");
    fclose(logfile);
}


int main(int argc, char *argv[]) {
	
	fprintf(stdout, "Hello client!\n");

	// IPC client code here
          char  *fname = {0};
        
        fname =(char *)malloc((strlen("logtest")+1)*sizeof(char));
        strcpy(fname,"logtest");
	
	// ...
    int shmid;
    key_t key;
    shmseg_t *shm;
    sem_t *signal_in, *signal_out;
    int number;
      int s;


     printf ("Enter your number: ");
     scanf ("%d",&number);
    /*
     * We need to get the segment named
     * "5678", created by the server.
     */
    key = 5678;

    /*
     * Locate the segment.
     */
    if ((shmid = shmget(key, sizeof(shmseg_t), 0666)) < 0) {
        
        exit(1);
    }

    /*
     * Now we attach the segment to our data space.
     */
    if ((shm = shmat(shmid, NULL, 0)) == (shmseg_t *) -1) {
        
        exit(1);
    }





    if ( (signal_in = sem_open(SEMAPHORE_INPUT, O_CREAT | O_EXCL, 0666,0)) == SEM_FAILED )
    {
            log_message(fname ,"Error sem_open");
            exit(1);
    }
    log_message(fname,"opened semaphore: %p", signal_in);
    if ( (signal_out = sem_open(SEMAPHORE_OUTPUT, O_CREAT | O_EXCL, 0666,0)) == SEM_FAILED )
    {
            log_message(fname ,"Error sem_open");
            exit(1);
    }

    (*shm).n = number;

    
        sem_getvalue(signal_in, &s);
        log_message(fname,"input=%d", s);
        log_message(fname,"posting");
        sem_post(signal_in);
        sem_getvalue(signal_in, &s);
        log_message(fname,"input=%d", s);
        sem_getvalue(signal_out, &s);
        log_message(fname,"output=%d", s);
        log_message(fname,"waiting sem_output");
        sem_wait(signal_out);
        sem_getvalue(signal_out, &s);
        log_message(fname,"sem_output=%d", s);
        printf("Result from ipcd: %d\n", (*shm).fibonacci);

     
        if (sem_close(signal_in))
        {
                log_message(fname ,"Error sem_close(sem_input): errno=%d, %s", errno, strerror(errno));
                exit(1);
        }
        if (sem_close(signal_out))
        {
                log_message(fname ,"Error sem_close(sem_output): errno=%d, %s", errno, strerror(errno));
                exit(1);
        }



        exit(0); 

}
